package com.cxh.rmsq.ui.activity.self

import android.Manifest
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.widget.EditText
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.net.toUri
import androidx.lifecycle.ViewModelProviders
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.ColorUtils
import com.cxh.rmsq.R
import com.cxh.rmsq.common.Constant
import com.cxh.rmsq.im.IMManager
import com.cxh.rmsq.model.Resource2
import com.cxh.rmsq.model.Status
import com.cxh.rmsq.ui.activity.MainActivity
import com.cxh.rmsq.ui.dialog.PhotoDialog
import com.cxh.rmsq.utils.ToastUtils
import com.cxh.rmsq.utils.permission.AppPermissionUtil
import com.cxh.rmsq.viewmodel.UserInfoViewModel
import com.github.gzuliyujiang.wheelpicker.DatePicker
import com.github.gzuliyujiang.wheelpicker.annotation.DateMode
import com.github.gzuliyujiang.wheelpicker.contract.OnDatePickedListener
import com.github.gzuliyujiang.wheelpicker.entity.DateEntity
import com.github.gzuliyujiang.wheelpicker.impl.UnitDateFormatter
import com.github.gzuliyujiang.wheelpicker.widget.DateWheelLayout
import com.xuexiang.xui.widget.imageview.RadiusImageView


class CompleteDataActivity : AppCompatActivity(), View.OnClickListener {

    var sex = -1
    var avatar = ""
    var birthday = ""
    private var photoDialog: PhotoDialog? = null

    private val ivBack: LinearLayout by lazy { findViewById<LinearLayout>(R.id.iv_back) }
    private val etName: EditText by lazy { findViewById<EditText>(R.id.et_name) }
    private val ivHead: RadiusImageView by lazy { findViewById<RadiusImageView>(R.id.iv_head) }
    private val ivPhoto: ImageView by lazy { findViewById<ImageView>(R.id.iv_photo) }
    private val tvBirthday: TextView by lazy { findViewById<TextView>(R.id.tv_birthday) }
    private val tvComplete: TextView by lazy { findViewById<TextView>(R.id.tv_complete) }
    private var userInfoViewModel: UserInfoViewModel? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_complete_data)
        findViewById<ConstraintLayout>(R.id.cl_toolbar).setPadding(
            0,
            BarUtils.getStatusBarHeight(),
            0,
            0
        )
        BarUtils.setStatusBarColor(this, ColorUtils.getColor(R.color.transparent))
        BarUtils.setStatusBarLightMode(this, true)

        userInfoViewModel =
            ViewModelProviders.of(this).get<UserInfoViewModel>(UserInfoViewModel::class.java)

        sex = intent.getIntExtra(Constant.SEX, -1)
        ivBack.setOnClickListener(this)
        findViewById<ImageView>(R.id.iv_photo).setOnClickListener(this)
        ivPhoto.setOnClickListener(this)
        tvBirthday.setOnClickListener(this)
        tvComplete.setOnClickListener(this)

        initAvatar()
        ininDate()
    }

    fun ininDate() {
        userInfoViewModel!!.upload()
            .observe(this@CompleteDataActivity) { resource: Resource2<String?> ->
                if (resource.status == Status.SUCCESS && resource.data != null) {
                    avatar = resource.data!!
                    Log.e("avatar", avatar)
                }
            }

    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.iv_back -> {
                finish()
            }

            R.id.iv_photo -> {
                AppPermissionUtil.requestPermissions(this@CompleteDataActivity,
                    arrayOf<String>(
                        Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE
                    ),
                    object : AppPermissionUtil.OnPermissionListener {
                        override fun onPermissionGranted() {
                            photoDialog?.show()
                        }

                        override fun onPermissionDenied() {

                        }

                    })
            }

            R.id.tv_birthday -> {
//                showDatePickerDialog()
                popBirthday()
            }

            R.id.tv_complete -> {
                val nickname = etName.text.toString()
                if (TextUtils.isEmpty(avatar)) {
                    ToastUtils.showToast("请上传头像")
                    return
                }
                if (TextUtils.isEmpty(nickname)) {
                    ToastUtils.showToast("请输入名字")
                    return
                }
                if (TextUtils.isEmpty(birthday)) {
                    ToastUtils.showToast("请选择出生日期")
                    return
                }
                userInfoViewModel!!.updateUserinfo(
                    avatar, nickname, sex.toString(), birthday,
                    "", "", "", "", "", "", null, "", "", "", "", "", ""
                )
                userInfoViewModel!!.updateUserinfo()
                    .observe(this@CompleteDataActivity) { resource: Resource2<String?> ->
                        if (resource.status == Status.SUCCESS && resource.data != null) {
                            startActivity(
                                Intent(
                                    this@CompleteDataActivity,
                                    MainActivity::class.java
                                )
                            )
                            finish()
                            // 存储当前登录成功的用户信息
//                            var info: UserCacheInfo? = null
//
//                             info = UserCacheInfo(IMManager.getInstance().currentId,
//                                 SPUtils.get(this, "accessToken", "").toString(),
//                                 userCache?.userCache?.phoneNumber,"86",
//                                 countryCache?.getCountryInfoByRegion("86"))
//
//                            userCache?.saveUserCache(info)
                            IMManager.getInstance()
                                .updateUserInfoCache(
                                    IMManager.getInstance().currentId,
                                    nickname,
                                    Uri.parse(avatar),
                                    ""
                                )

                        }
                    }
            }
        }
    }

    private fun initAvatar() {
        if (photoDialog == null) {
            photoDialog =
                PhotoDialog(this@CompleteDataActivity, true, 1, 1, R.style.BottomDialog)
        }

        photoDialog?.setOnClickListener(object : PhotoDialog.OnClickListener {
            override fun onPhotoPathResult(images: MutableList<String>) {
                ivHead.setImageURI(images[0].toUri())

                userInfoViewModel!!.uploadImg(images[0])
            }

            override fun onCameraPathResult(images: MutableList<String>) {
                ivHead.setImageURI(images[0].toUri())

                userInfoViewModel!!.uploadImg(images[0])
            }

        })
    }

    private fun popBirthday() {
        val picker = DatePicker(this)
        picker.setTitle("请选择生日")
        val wheelLayout: DateWheelLayout = picker.getWheelLayout()
        wheelLayout.setDateMode(DateMode.YEAR_MONTH_DAY)
        //        wheelLayout.setDateLabel("年", "月", "日");
        wheelLayout.setDateFormatter(UnitDateFormatter())
        wheelLayout.setRange(DateEntity.target(1970, 1, 1), DateEntity.today(), DateEntity.today())
        //        wheelLayout.setCurtainEnabled(true);
        picker.getWheelLayout().setResetWhenLinkage(false)
        picker.setOnDatePickedListener(object : OnDatePickedListener {
            override fun onDatePicked(year: Int, month: Int, day: Int) {
                val stringBuilder = StringBuilder()
                stringBuilder.append(year).append("-")
                if (month < 10) {
                    stringBuilder.append("0")
                }
                stringBuilder.append(month).append("-")
                if (day < 10) {
                    stringBuilder.append("0")
                }
                stringBuilder.append(day)
                tvBirthday.setText(stringBuilder)
                birthday = tvBirthday.text.toString()
            }
        })
        picker.show()
    }

}